package com.hot100.mid;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhengTao
 * @version 1.0
 * @description:   合并区间
 * @date 2022/8/11 14:52
 */
public class Demo19 {
    public static void main(String[] args) {
        int[][] a={{1,3},{8,10},{2,6},{20,18}};
        merge(a);
    }

    public static int[][] merge(int[][] intervals) {
        if(intervals.length<=1){
            return intervals;
        }
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        for (int[] interval : intervals) {
            Arrays.sort(interval);
            System.out.println(interval);
        }
        List<int[]> resList=new ArrayList<>();
        for (int[] interval : intervals) {
            if(resList.size()==0||resList.get(resList.size()-1)[1]<interval[0]){
                resList.add(interval);
            }else {
                resList.get(resList.size())[1]=Math.max(resList.get(resList.size() - 1)[1],interval[1]);
            }
        }
        return resList.toArray(new int[0][]);
    }
}
